package com.summer.framework.core.category;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 *
 * @auther Ice Yang
 * Date 2025/9/30 15:18
 */
@Component
public class CategorySerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        List<BeanPropertyWriter> need = new ArrayList<>();
        for (BeanPropertyWriter writer : beanProperties) {
            CategoryField dictAnnotation = writer.getAnnotation(CategoryField.class);
            if (dictAnnotation != null) {
                // 为每个有@CategoryFiled注解的字段添加对应的标签字段
                need.add(addLabelProperty(config, writer, dictAnnotation, beanDesc));
            }
        }
        beanProperties.addAll(need);
        return beanProperties;
    }

    private BeanPropertyWriter addLabelProperty(SerializationConfig config,
                                  BeanPropertyWriter originalWriter, CategoryField dictAnnotation, BeanDescription beanDesc) {

        String originalFieldName = originalWriter.getName();
        String labelFieldName = getLabelFieldName(dictAnnotation, originalFieldName);

        CategorySerializer serializer = new CategorySerializer();
        serializer.init(originalWriter,dictAnnotation.type(),dictAnnotation.group());
        // 创建标签字段的PropertyWriter
        return new BeanPropertyWriter(
                SimpleBeanPropertyDefinition.construct(
                        config,
                        originalWriter.getMember(),
                        new PropertyName(labelFieldName)
                ),
                originalWriter.getMember(),
                beanDesc.getClassInfo().getAnnotations(),
                originalWriter.getType(),
                serializer,
                null,
                originalWriter.getType(),
                originalWriter.willSuppressNulls(),
                null,
                originalWriter.getViews()
        );
    }

    private String getLabelFieldName(CategoryField dictAnnotation, String originalFieldName) {
        if (!dictAnnotation.target().isEmpty()) {
            return dictAnnotation.target();
        }
        return originalFieldName + "Text";
    }
}
